#!/bin/bash
#
# usage: steering.sh obs,OBS min max step run_card.dat n_runs [--keepruncard] [--keepparamcard] [-f] [--diagonal=ebeam2]
#

# usage: steering.sh aS 0.118 0.123 0.001 param_card.dat 0 ! -dry is optional and must be after all the physics paramters
# usage: steering.sh ptj 150.0 700.0 150.0 run_card.dat 1
# usage: steering.sh htjmin,htjmax 250.0 3300.0 150.0 run_card.dat 1
# usage: steerung.sh ht2min,ht2max 250.0 300.0 25.0 run_car.dat 1
# usage: steering.sh ptj 150.0 700.0 150.0 run_card.dat 0
# usage: steering.sh ebeam1 3500,4000,7000,50000 700.0 150.0 run_card.dat 0 --diagonal=ebeam2
#
#help generate_events
#syntax: generate_events [run_name] [options])
#-- Launch the full chain of script for the generation of events
#   Including possible plotting, shower and detector resolution.
#   Those steps are performed if the related program are installed
#   and if the related card are present in the Cards directory.
#-- local options:
#      -f : Use default for all questions.
#      --laststep= : argument might be parton/pythia/pgs/delphes and indicate the last level to be run.
#-- session options:
#      Note that those options will be kept for the current session
#      --cluster : Submit to the  cluster. Current cluster: condor
#      --multicore : Run in multi-core configuration
#      --nb_core=X : limit the number of core to use to X.
#
################ Colors ################
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
RED=$ESC_SEQ"31;01m"
GREEN=$ESC_SEQ"32;01m"
YELLOW=$ESC_SEQ"33;01m"
BLUE=$ESC_SEQ"34;01m"
MAGENTA=$ESC_SEQ"35;01m"
CYAN=$ESC_SEQ"36;01m"
########################################
echo -e $GREEN"the output folder will be"
dateofrun=`date +"%Y-%m-%d--%H-%M"`
tempfoldername="$@""__"$dateofrun
outputfolder=`echo output/"$tempfoldername" | sed 's/ /_/g'`
echo $outputfolder
echo -e $COL_RESET

argCounter=1;
leaveruncard=false
leaveparamcard=false
batchrun=false
diagonalrun=false
laststepmg=parton
removepythia=true

for iarg in $*; do
    CLIinputs[$argCounter]=$iarg
    option=`echo "$iarg" | cut -d"=" -f1`

    if [ "$iarg" == "--keepruncard" ]; then
	leaveruncard=true
    fi

    if [ "$iarg" == "--keepparamcard" ]; then
	leaveparamcard=true
    fi

    if [ "$iarg" == "-f" ]; then
	batchrun=true
    fi

    if [ "$option" == "--diagonal" ]; then
     	diagonalrun=true
     	diagonalparamter=`echo "$iarg" | cut -d"=" -f2`
     	echo -e "the paramter "$RED$diagonalparamter$COL_RESET" will be changed together with "$RED$1$COL_RESET
     fi


    if [ "$option" == "--laststep" ]; then
     	laststepmg=`echo "$iarg" | cut -d"=" -f2`
     	echo -e "the last step of the run is "$RED$laststepmg$COL_RESET
    fi

    if [ "$option" == "-h" ]; then
     	echo "available options:"
	echo "--keepruncard"
	echo "--keepparamcard"
	echo "-f"
	echo "--diagonal"
	echo "--laststep=parton/pythia/pgs/delphes (default is parton)"
     fi

    let argCounter=argCounter+1
done

echo "The inputs are "${CLIinputs[*]}

if [ "$leaveruncard" = true ]; then
    echo -e $RED"The run_card will not be restored at the end of the run"$COL_RESET
fi
if [ "$leaveparamcard" = true ]; then
    echo -e $RED"The param_card will not be restored at the end of the run"$COL_RESET
fi

#echo "The inputs are "${CLIinputs[*]}

if [ ! -d output ]; then
    # Control will enter here if $DIRECTORY doesn't exist.
    mkdir output
fi

if [ ! -d "$outputfolder" ]; then
    # Control will enter here if $DIRECTORY doesn't exist.
    mkdir $outputfolder
fi

newobs=$1

newobsmin=`echo $newobs | cut -d "," -f1`
newobsmax=`echo $newobs | cut -d "," -f2`



if [ $newobsmin == $newobsmax ]; then
    echo "scan 1d of just one paramter"
    newobsmax=""
fi

newstart=$2
newend=$3
newstep=$4

card=$5

numberofruns=$6

echo $newobsmin $newobsmax $newstart $newend $newstep

obsmin=$newobsmin
obsmax=$newobsmax
# scanning range
start=$newstart
end=$newend
step=$newstep
#
#
#
#

newstartone=`echo $newstart | cut -d "," -f1`
newstarttwo=`echo $newstart | cut -d "," -f2`

if [ $newstartone == $newstarttwo ]; then
  
    echo "scan by constant binning of just one paramter"
    
    
    last=$start
    binlowends[0]=$start
    COUNTER=1
    while [  $(echo $last + $step \<= $end | bc) -eq 1 ]; do
	
	#             echo The parameter is ` printf %e $low`
	
        low=$(echo $last + $step | bc)
        #echo The parameter is $low
	last=$low
	if [ $(echo $low \< 1 | bc) -eq 1 ]; then
	    binlowends[$COUNTER]=`echo 0$low`
	else 
	    binlowends[$COUNTER]=$low
	fi
	let COUNTER=COUNTER+1 
    done
    histosize=$COUNTER
else
    echo "attempting to use "$newstart
    OIFS=$IFS;
    IFS=",";

    
    binlowends=($newstart);
    
    for ((i=0; i<${#binlowends[@]}-1; ++i));
    do
	echo "run $i: ${binlowends[$i]}-->${binlowends[$i+1]}";
    done

    IFS=$OIFS;
    histosize=$(echo ${#binlowends[@]} - 1 | bc)
fi

#echo The final counter is $COUNTER
#echo The final bin is $low



echo -e $RED"Will use the following paramters in the run_cards:"
echo -e ${binlowends[*]}$COL_RESET # print all

echo ${#binlowends[@]} # return size 

#there are runs to be made!
if [ ${#binlowends[@]} -gt 0 ]; then 
    rm run_card.dat.run*
    rm param_card.dat.run*
    
    cp Cards/run_card.dat .
    cp Cards/param_card.dat .
    
    cp run_card.dat run_card.dat.original
    cp param_card.dat param_card.dat.original

    # find the run_name in the current run card and prompt if that is ok 
    currentrunname=`grep -e run_tag run_card.dat | cut -d "=" -f1 | tr -d " "`
    defaultrunname=$currentrunname
    if [ "$batchrun" = false ]; then
	echo -e "This is an interactive run"
	####################################
	echo -e "The current run_tag is "$MAGENTA$currentrunname$COL_RESET
	echo -n "use it? (return=yes, or type new one) " && read currentrunname && echo $currentrunname
	baserunname=${currentrunname:-$defaultrunname}
	
	#baserunname=$currentrunname
    else
	baserunname=$defaultrunname
    fi
    
    COUNTER=0
    while [  $COUNTER -lt $(echo $histosize | bc) ]; do
        #echo The counter is $COUNTER
	
	
	if [ "$obsmax" = "" ]; then
	    echo ${binlowends[$COUNTER]} 
	    params=($obsmin ${binlowends[$COUNTER]} )
	fi
	if [ "$obsmax" != "" ]; then 
	    echo ${binlowends[$COUNTER]} "-->" ${binlowends[$COUNTER+1]} 
	    params=($obsmin ${binlowends[$COUNTER]} $obsmax ${binlowends[$COUNTER+1]})
	fi
     paramsize=${#params[@]}
     
     echo -e $RED"There are "$(echo ${#params[@]}/2 | bc)" changes to be made to the card."
     echo -e ${params[*]}
     echo -e $COL_RESET
     runnameappend=`echo -e ${params[*]} |  sed -e 's/ /_/g'`
     runnames[$COUNTER]=$runnameappend

     
     # write all the cards
	     COUNTERparam=0
	     while [  $COUNTERparam -lt $paramsize ]; do
		 echo -e $BLUE"Making change "$COUNTERparam":"${params[$COUNTERparam]} ${params[$COUNTERparam+1]}$COL_RESET 
		 
		 set_madgraph_parameter.sh ${params[$COUNTERparam]} ${params[$COUNTERparam+1]} $card
		  if [ "$diagonalrun" = true ]; then
		      if [ "${params[$COUNTERparam]}" = "$1" ]; then
		       	  set_madgraph_parameter.sh $diagonalparamter ${params[$COUNTERparam+1]} $card
		      fi
		  fi
		 let COUNTERparam=COUNTERparam+2 
	     done
	     # run_tag is always updated in the run_card.dat
	     set_madgraph_parameter.sh  run_tag $baserunname"_run"$(($COUNTER+1))"_"$runnameappend run_card.dat
	     # since run_tag is always updated the run_card needs to be changed in all runs
	     cp run_card.dat run_card.dat.run$COUNTER
	     # if param_card.dat was modified prepare the param_card.dat
	     if [ "$card" = "param_card.dat" ]; then 
		 cp param_card.dat param_card.dat.run$COUNTER
	     fi
	     
	     let COUNTER=COUNTER+1 
	     
    done
    ############################
    #all cards have been written
    ############################
    #
    ####################################
    # copy the cards and run one by one (or send it in many places, but not yet in this version!)
    ####################################
    # the difference is that in order to run parallel the folder needs to be duplicted each time and the cards need to be run in that folder in parallel
    # using xargs? or parallel? I don't know yet
    COUNTER=1
    while [  $COUNTER -le $(echo $histosize | bc) ]; do
	if [ "$card" = "param_card.dat" ]; then 
	    cp  param_card.dat.run$(($COUNTER-1)) Cards/param_card.dat
	fi
	cp run_card.dat.run$(($COUNTER-1)) Cards/run_card.dat

#add a run_name instead of the default?	
	if [ $numberofruns -gt 0 ]; then
	    if [ $numberofruns -eq 1 ]; then
		MGrunname="run"$COUNTER"_of_"$histosize"__"${runnames[$(($COUNTER-1))]}"__"$dateofrun
	        #./bin/generate_events $MGrunname  -f --laststep=parton
	        ./bin/generate_events $MGrunname  -f --laststep="$laststepmg"
		if [ "$removepythia" = true ]; then
		   find . -iname *pythia_events.hep* -exec rm {} \;
		   find . -iname *pythia_lhe_events.root* -exec rm {} \;
		   find . -iname *delphes_events.root* -exec rm {} \;
		fi
		if [ "$newobsmax" != "" ]; then
		    cd Events/$MGrunname
		    outputfilename=`ls *.txt | rev | cut -d"." -f2- | cut -c8- | rev`
		    cd ../..
		    ln -v -s ../../Events/$MGrunname/unweighted_events.root ./$outputfolder/$outputfilename.root
		fi
	    else 
		# DOING MULTI_RUN
                #./bin/madevent multi_run $numberofruns -f --laststep=parton 
		./bin/madevent multi_run $numberofruns -f --laststep="$laststepmg" 
		if [ "$removepythia" = true ]; then
		   find . -iname *pythia_events.hep* -exec rm {} \;
		   find . -iname *pythia_lhe_events.root* -exec rm {} \;
		   find . -iname *delphes_events.root* -exec rm {} \;
		fi
	    fi
	fi
	
	let COUNTER=COUNTER+1 
    done
    
    # restore the original run_card
    if [ "$leaveruncard" = false ]; then
	echo -e $RED"The run_card.dat is going to be restored."
	cp -v run_card.dat.original ./Cards/run_card.dat
	echo -e $COL_RESET
    fi

    if [ "$leaveparamcard" = false ]; then
	echo -e $RED"The param_card.dat is going to be restored."
	cp -v param_card.dat.original ./Cards/param_card.dat
	echo -e $COL_RESET
    fi
    	
fi
